<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2006
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
*	SEARCHMETADATA class
*
*	Search database metadata on a variety of parameters.
*
*	Example:  if quotes and quote comments are being searched on, display comment under the quote if commenting on that particular quote.
*
*	$Header: /cvsroot/wikindx/wikindx3/core/list/SEARCHMETADATA.php,v 1.15 2006/07/17 22:06:58 sirfragalot Exp $
*****/
class SEARCHMETADATA
{
// Constructor
	function SEARCHMETADATA($db, $vars)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/html/MISC.php");
		include_once("core/html/FORM.php");
		include_once("core/html/TABLE.php");
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
		include_once("core/list/LISTCOMMON.php");
		$this->common = new LISTCOMMON($this->db, $this->vars);
		include_once("core/html/HTML.php");
		$this->html = new HTML();
	}
// display form options
	function display($error = FALSE)
	{
		$this->template->setVar('heading', $this->messages->text("heading", "searchMeta"));
///First check, do we have resources?
		$recordset = $this->db->select(array('WKX_database_summary'), array('totalResources'));
		if(!$this->db->fetchOne($recordset))
		{
			$this->template->setVar('body', $this->messages->text('misc', 'noResources'));
			return $this->template->process();
		}
		$this->userBib = $this->session->getVar("mywikindx_bibliography_use");
		$bib = FALSE;
		if($this->userBib)
		{
			$recordset = $this->db->select(array('WKX_user_bibliography'), array('title'), 
				" WHERE " . $this->db->formatfield('id') . "=" . $this->db->tidyInput($this->userBib));
			$row = $this->db->fetchRow($recordset);
			$bib = MISC::p(MISC::span("(" . $this->messages->text("user", "bibliography") . ": " . 
				$row['title'] . ")", "hint"));
		}
		else if($this->session->getVar('setup_multiUser'))
			$bib = MISC::p(MISC::span("(" . $this->messages->text("user", "bibliography") . ": " . 
			$this->messages->text("user", "masterBib") . ")", "hint"));
// load the session
		$sessionVars = $this->session->getArray("searchMeta");
		$pString = $error ? $error : FALSE;
		$pString .= $bib;
		$this->template->setVar('formStart', FORM::formHeader("searchMetaProcess"));
		$pString .= TABLE::tableStart();
		$pString .= TABLE::trStart();
/*
		$this->grabTypes();
// add 0 => IGNORE to $array
		$temp[0] = $this->messages->text("misc", "ignore");
		foreach($this->type as $key => $value)
			$temp[$key] = $value;
		if($selected = $this->session->getVar("search_type"))
		{
			$selectedArray = explode(",", $selected);
			$pString .= TABLE::td(FORM::selectedBoxValueMultiple(
			$this->messages->text("search", "member", " " . 
			$this->messages->text("search", "type")), "search_type", $temp, $selectedArray, 5) . 
			MISC::br() . $this->messages->text("hint", "multiples") . MISC::br());
		}
		else
			$pString .= TABLE::td(FORM::selectFBoxValueMultiple(
			$this->messages->text("search", "member", " " . 
			$this->messages->text("search", "type")), "search_type", $temp, 5) . 
			MISC::br() . $this->messages->text("hint", "multiples") . MISC::br());
		$this->grabGroups();
		$pString .= TABLE::td($this->makeFormMultiple("category", $this->group));
// There may not yet be keywords in the database.
		$this->grabKeywords();
		if($this->keyword)
			$pString .= TABLE::td($this->makeFormMultiple("keyword", $this->keyword));
		else
			$pString .= TABLE::td("&nbsp;");
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		$pString .= MISC::br() . "&nbsp;" . MISC::hr() . MISC::br();
		$pString .= TABLE::tableStart();
		$pString .= TABLE::trStart();
*/
// array of database fields that can be searched on:
		$this->radioButtons = FALSE;
		$fields = array("quote"	=>	$this->messages->text("metadata", "quotes"),
				"quoteComment"	=>	$this->messages->text("metadata", "quoteComments"),
				"paraphrase"	=>	$this->messages->text("metadata", "paraphrases"),
				"paraphraseComment"	=>	$this->messages->text("metadata", "paraphraseComments"),
				"musing"	=>	$this->messages->text("metadata", "musings"),
			);
//		$this->makeRadioButtons('field');
		$pString .= TABLE::td($this->makeFormMultiple("field", $fields, TRUE));
// There may not yet be keywords in the database.
		$this->grabKeywords();
		if($this->keyword)
			$pString .= TABLE::td($this->makeFormMultiple("keyword", $this->keyword));
		else
			$pString .= TABLE::td("&nbsp;");
		$word = $this->session->issetVar("searchMeta_word") ? 
			stripslashes($this->session->getVar("searchMeta_word")) : FALSE;
		$checked = $this->session->issetVar("searchMeta_partial") ? 'CHECKED' : FALSE;
		$pString .= TABLE::td(FORM::textInput($this->messages->text("search", "word"), "searchMeta_word", 
			$word, 40) . " " . MISC::span('*', 'required') . 
			MISC::p($this->messages->text("search", "partial") . ":&nbsp;&nbsp;" . 
			FORM::checkbox(FALSE, "searchMeta_partial", $checked)));
// array of search methods:
		$methods = array("OR"		=>	"OR",
				"AND"		=>	"AND",
				"exact"		=>	$this->messages->text("search", "exact"),
			);
		if($selected = $this->session->getVar("searchMeta_method"))
			$pString .= TABLE::td(FORM::selectedBoxValue(
			$this->messages->text("search", "search", " " . 
			$this->messages->text("search", "method")), "searchMeta_method", $methods, $selected, 3));
		else
			$pString .= TABLE::td(FORM::selectFBoxValue(
			$this->messages->text("search", "search", " " . 
			$this->messages->text("search", "method")), "searchMeta_method", $methods, 3));
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		if(is_array($this->session->getArray("searchMeta")))
		{
			$this->session->clearArray("searchMeta");
			$reset = FORM::formHeader("searchMetaDisplay") . 
				FORM::formSubmit("Reset") . FORM::formEnd();
			$pString .= MISC::p(FORM::formSubmit("Proceed") . FORM::formEnd() . $reset);
		}
		else
			$pString .= MISC::br() . FORM::formSubmit("Search") . MISC::br() . MISC::br() . 
			FORM::formReset() . FORM::formEnd();
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
// make a multiple select box
	function makeFormMultiple($type, $array, $noIgnore = FALSE)
	{
// add 0 => IGNORE to $array
		if(!$noIgnore)
		{
			$temp[0] = $this->messages->text("misc", "ignore");
			foreach($array as $key => $value)
				$temp[$key] = $value;
		}
		else
			$temp = $array;
//		if(($type == 'category') || ($type == 'keyword') || ($type == 'type'))
		if($type == 'keyword')
			$label = 'member';
		else
			$label = 'search';
		if($selected = $this->session->getVar("searchMeta_" . $type))
		{
			$selectedArray = explode(",", $selected);
			$pString = FORM::selectedBoxValueMultiple(
				$this->messages->text("search", $label, " " . 
				$this->messages->text("search", $type)), 
				"searchMeta_" . $type, $temp, $selectedArray, 5);
		}
		else
		{
// If $type == 'field', select all fields as default
			if($type == 'field')
			{
				$pString = FORM::selectedBoxValueMultiple(
					$this->messages->text("search", $label, " " . 
					$this->messages->text("search", $type)), 
					"searchMeta_" . 'field', $temp, array_keys($array), 5);
			}
			else
				$pString = FORM::selectFBoxValueMultiple(
					$this->messages->text("search", $label, " " . 
					$this->messages->text("search", $type)), 
					"searchMeta_" . $type, $temp, 5);
		}
		$pString .= MISC::br() . $this->messages->text("hint", "multiples") . MISC::br();
		$pString .= $this->radioButtons . MISC::br();
		return $pString;
	}
/*
// get types from database.
	function grabTypes()
	{
		include_once("core/resource/RESOURCEMAP.php");
		$resourceMap = new RESOURCEMAP();
		include_once("core/messages/UTF8.php");
		$this->utf8 = new UTF8();
		foreach($resourceMap->types as $key)
			$this->type[$key] = $this->utf8->encodeUtf8($this->messages->text("resourceType", $key));
		$this->makeRadioButtons('type');
	}
// get groups from database.
	function grabGroups()
	{
		include_once("core/group/GROUP.php");
		$group = new GROUP($this->db);
		$this->group = $group->grabAll();
		$this->makeRadioButtons('category');
	}
*/
// get keywords from database.
	function grabKeywords()
	{
// Load groups
		include_once("core/keyword/KEYWORD.php");
		$keyword = new KEYWORD($this->db);
		$userBib = $this->session->getVar("mywikindx_bibliography_use");
		$this->keyword = $keyword->grabmeta();
		$this->makeRadioButtons('keyword');
	}
// Create radio buttons for AND and OR
	function makeRadioButtons($type)
	{
		$type = 'searchMeta_' . $type . 'Method';
		if($this->session->getVar($type) == 'AND')
		{
			$pString = MISC::span(FORM::radioButton(FALSE, $type, 'OR') . " OR", "small") . MISC::br();
			$pString .= MISC::span(FORM::radioButton(FALSE, $type, 'AND', TRUE) . " AND", "small");
		}
// Default
		else
		{
			$pString = MISC::span(FORM::radioButton(FALSE, $type, 'OR', TRUE) . " OR", "small") . 
				MISC::br();
			$pString .= MISC::span(FORM::radioButton(FALSE, $type, 'AND') . " AND", "small");
		}
		$this->radioButtons = $pString;
	}
// parse the search word(s)
	function parseWord($input)
	{
		include_once("core/messages/UTF8.php");
		$utf8 = new UTF8();
		if(($input['method'] == 'OR') || ($input['method'] == 'AND'))
			$string = explode(" ", $utf8->smartUtf8_encode(trim($input['word'])));
		else
			$string = array($utf8->smartUtf8_encode(trim($input['word'])));
//		foreach($string as $term)
//			$terms[] = utf8_encode(trim($term));
		$this->session->setVar("searchMeta_highlight", implode(",", $string));
// partial or complete word searching?
		if(array_key_exists('partial', $input))
		{
			foreach($string as $word)
				$this->words[] = " LIKE '%" . trim($word) . "%'";
		}
		else
		{
			foreach($string as $word)
				$this->words[] = " REGEXP '[[:<:]]" . trim($word) . "[[:>:]]'";
		}
	}
// add to SQL conditional statement and add fields to fieldArray for database fields
	function fieldSql($input)
	{
		if(!array_key_exists('field', $input))
			return;
		$this->stmtQuote = $this->stmtQuoteComment = $this->stmtParaphrase = $this->stmtParaphraseComment = 
			$this->stmtMusing = FALSE;
		$fields = explode(",", $input['field']);
		foreach($fields as $field)
		{
			$conditionArray = array();
/*			if($field == 'title')
			{
				foreach($this->words as $word)
					$condition[] = $this->db->formatField('WKX_resource.title') . $word . 
						" OR " . 
						$this->db->formatField('subtitle') . $word;
//					$condition[] = $this->db->concat(
//						array($this->db->formatField('WKX_resource.title'), 
//						$this->db->tidyInputNoTrim(" "), 
//						$this->db->formatField('subtitle'))) . $word;
//					$condition[] = "CONCAT_WS(' ', WKX_resource.title, " . 
//					$this->db->formatField('subtitle') . ") " . $word;
				$conditionArray[] = "(" . implode(' ' . $input['method'] . ' ', $condition) . ")";
			}
			else if($field == 'note')
			{
				$this->fieldArray = array_merge($this->fieldArray, 
					array(array('WKX_resource_note.text' => "note")));
				foreach($this->words as $word)
					$condition[] = 'WKX_resource_note.text' . $word;
				$conditionArray[] = "(" . implode(' ' . $input['method'] . ' ', $condition) . ")";
			}
			else if($field == 'abstract')
			{
				$this->fieldArray = array_merge($this->fieldArray, array('abstract'));
				foreach($this->words as $word)
					$condition[] = 'WKX_resource_abstract.abstract' . $word;
				$conditionArray[] = "(" . implode(' ' . $input['method'] . ' ', $condition) . ")";
			}
*/
			if($field == 'quote')
			{
				foreach($this->words as $word)
					$conditionArray[] = $this->db->formatfield("text") . $word;
				$condition = " WHERE (" . implode(' ' . $input['method'] . ' ', $conditionArray) . ")";
				$this->stmtQuote = $this->db->selectNoExecute(array('WKX_resource_quote'), 
					array(array("WKX_resource_quote.id" => 'quoteId'), 'resourceId', 'text',
					'page_start', 'page_end', 'surname'), 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource') . 
						" ON " . $this->db->formatfield("resourceId") . "=" . 
						$this->db->formatfield("WKX_resource.id") . 
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_quote_text") .  
						" ON " . $this->db->formatfield("WKX_resource_quote.id") . "=" . 
						$this->db->formatfield("WKX_resource_quote_text.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource_creator') . " ON " . 
					$this->db->formatfield("resourceId") . "=" . 
					$this->db->formatfield("WKX_resource_creator.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_creator') . " ON " . 
					$this->db->formatfield("WKX_resource_creator.creator1") . "=" . 
					$this->db->formatfield("WKX_creator.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource_year') . " ON " . 
					$this->db->formatfield("resourceId") . "=" . 
					$this->db->formatfield("WKX_resource_year.id") . 
					$condition);
			}
			else if($field == 'quoteComment')
			{
				foreach($this->words as $word)
					$conditionArray[] = $this->db->formatfield("comment") . $word;
				$condition = " WHERE (" . implode(' ' . $input['method'] . ' ', $conditionArray) . ")";
				$this->stmtQuoteComment = $this->db->selectNoExecute(array('WKX_resource_quote_comment'), 
					array(array("WKX_resource_quote_comment.id" => 'commentId'), 'quoteId', 'resourceId', 
						'comment', 'quotePrivate', 'WKX_resource_quote_comment.addUserIdQuote', 
						'page_start', 'page_end'), 
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_quote") .  
						" ON " . $this->db->formatfield("WKX_resource_quote.id") . "=" . 
						$this->db->formatfield("WKX_resource_quote_comment.quoteId") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource') . 
						" ON " . $this->db->formatfield("resourceId") . "=" . 
						$this->db->formatfield("WKX_resource.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource_creator') . " ON " . 
					$this->db->formatfield("resourceId") . "=" . 
					$this->db->formatfield("WKX_resource_creator.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_creator') . " ON " . 
					$this->db->formatfield("WKX_resource_creator.creator1") . "=" . 
					$this->db->formatfield("WKX_creator.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource_year') . " ON " . 
					$this->db->formatfield("resourceId") . "=" . 
					$this->db->formatfield("WKX_resource_year.id") . 
					$condition);
			}
			else if($field == 'paraphrase')
			{
				foreach($this->words as $word)
					$conditionArray[] = $this->db->formatfield("text") . $word;
				$condition = " WHERE (" . implode(' ' . $input['method'] . ' ', $conditionArray) . ")";
				$this->stmtParaphrase = $this->db->selectNoExecute(array('WKX_resource_paraphrase'), 
					array(array("WKX_resource_paraphrase.id" => 'paraphraseId'), 'resourceId', 'text', 
					'page_start', 'page_end'), 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource') . 
						" ON " . $this->db->formatfield("resourceId") . "=" . 
						$this->db->formatfield("WKX_resource.id") . 
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_paraphrase_text") .  
						" ON " . $this->db->formatfield("WKX_resource_paraphrase.id") . "=" . 
						$this->db->formatfield("WKX_resource_paraphrase_text.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource_creator') . " ON " . 
					$this->db->formatfield("resourceId") . "=" . 
					$this->db->formatfield("WKX_resource_creator.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_creator') . " ON " . 
					$this->db->formatfield("WKX_resource_creator.creator1") . "=" . 
					$this->db->formatfield("WKX_creator.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource_year') . " ON " . 
					$this->db->formatfield("resourceId") . "=" . 
					$this->db->formatfield("WKX_resource_year.id") . 
					$condition);
			}
			else if($field == 'paraphraseComment')
			{
				foreach($this->words as $word)
					$conditionArray[] = $this->db->formatfield("comment") . $word;
				$condition = " WHERE (" . implode(' ' . $input['method'] . ' ', $conditionArray) . ")";
				$this->stmtParaphraseComment = 
					$this->db->selectNoExecute(array('WKX_resource_paraphrase_comment'), 
					array(array("WKX_resource_paraphrase_comment.id" => 'commentId'), 'resourceId',  
						'paraphraseId', 'comment', 'paraphrasePrivate', 
						'WKX_resource_paraphrase_comment.addUserIdParaphrase', 'page_start', 'page_end'), 
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_paraphrase") .  
						" ON " . $this->db->formatfield("WKX_resource_paraphrase.id") . "=" . 
						$this->db->formatfield("WKX_resource_paraphrase_comment.paraphraseId") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource') . 
						" ON " . $this->db->formatfield("resourceId") . "=" . 
						$this->db->formatfield("WKX_resource.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource_creator') . " ON " . 
					$this->db->formatfield("resourceId") . "=" . 
					$this->db->formatfield("WKX_resource_creator.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_creator') . " ON " . 
					$this->db->formatfield("WKX_resource_creator.creator1") . "=" . 
					$this->db->formatfield("WKX_creator.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource_year') . " ON " . 
					$this->db->formatfield("resourceId") . "=" . 
					$this->db->formatfield("WKX_resource_year.id") . 
					$condition);
			}
			else if($field == 'musing')
			{
				foreach($this->words as $word)
					$conditionArray[] = $this->db->formatfield("text") . $word;
				$condition = " WHERE (" . implode(' ' . $input['method'] . ' ', $conditionArray) . ")";
				$this->stmtMusing = $this->db->selectNoExecute(array('WKX_resource_musing'), 
					array(array("WKX_resource_musing_text.id" => 'commentId'), 'resourceId', 
						'text', 'musingPrivate', 'addUserIdMusing', 'page_start', 'page_end'), 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource') . 
						" ON " . $this->db->formatfield("resourceId") . "=" . 
						$this->db->formatfield("WKX_resource.id") . 
					" LEFT JOIN " . $this->db->formatTable("WKX_resource_musing_text") .  
						" ON " . $this->db->formatfield("WKX_resource_musing.id") . "=" . 
						$this->db->formatfield("WKX_resource_musing_text.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource_creator') . " ON " . 
					$this->db->formatfield("resourceId") . "=" . 
					$this->db->formatfield("WKX_resource_creator.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_creator') . " ON " . 
					$this->db->formatfield("WKX_resource_creator.creator1") . "=" . 
					$this->db->formatfield("WKX_creator.id") . 
					" LEFT JOIN " . $this->db->formatTable('WKX_resource_year') . " ON " . 
					$this->db->formatfield("resourceId") . "=" . 
					$this->db->formatfield("WKX_resource_year.id") . 
					$condition);
			}
		}
	}
/*
// add to SQL conditional statement and add fields to fieldArray for resource types
	function typeSql($input)
	{
		if(!array_key_exists('type', $input))
			return;
		$types = explode(",", $input['type']);
		foreach($types as $type)
			$conditionArray[] = $this->db->formatField('type') . "=" . $this->db->tidyInput($type);
		$this->condition[] = "(" . implode(' OR ', $conditionArray) . ")";
	}

// add to SQL conditional statement and add fields to fieldArray for categories
	function groupSql($input)
	{
		if(!array_key_exists('category', $input))
			return;
		$this->fieldArray = array_merge($this->fieldArray, array('categories'));
		$groups = explode(",", $input['category']);
// NB MySQL bug: http://bugs.mysql.com/bug.php?id=2047 -- append comma temporarily
		foreach($groups as $group)
			$conditionArray[] = "FIND_IN_SET(" . $this->db->tidyInput($group) . ", CONCAT(" . 
				$this->db->formatField('categories') . ", ','))";
		$this->condition[] = "(" . implode(' ' .  $input['categoryMethod'] . ' ', $conditionArray) . ")";
	}
*/
// add to SQL conditional statement and add fields to fieldArray for keywords
	function keywordSql($input)
	{
		$this->kwq = $this->kwp = $this->kwm = FALSE;
		if(!array_key_exists('keyword', $input))
			return;
		include_once("core/keyword/KEYWORD.php");
		$kw = new KEYWORD($this->db);
		$this->kwq = " AND (" . $kw->selectConditionMetadata($input, 'quote') . ")";
		$this->kwp = " AND (" . $kw->selectConditionMetadata($input, 'paraphrase') . ")";
		$this->kwm = " AND (" . $kw->selectConditionMetadata($input, 'musing') . ")";
	}
	function process($output)
	{
		$input = $this->checkInput();
		include_once("core/list/LISTMETADATACOMMON.php");
		$this->metadataCommon = new LISTMETADATACOMMON($this->db, $this->vars, $output);
		if($output == 'html')
			$this->template->setVar('heading', $this->messages->text("heading", "searchMeta"));
		else if($output == 'rtf')
			$this->template->setVar('heading', $this->messages->text("heading", "exportRtf"));
		$this->parseWord($input);
		$this->fieldSql($input);
		$this->patterns = array();
//		$this->typeSql($input);
//		$this->groupSql($input);
		$this->keywordSql($input);
		$searchTerms = explode(",", $this->session->getVar('searchMeta_highlight'));
		foreach($searchTerms as $term)
			$this->patterns[] = "/($term)/i";
		$pString = $this->executeStmts($output);
		$this->session->setVar("sql_lastMultiMeta", 'search');
		$this->template->setVar('body', $pString);
//		$this->template->setVar('paging', $pagingString);
		return $this->template->process();
	}
// Execute each statement and concatenate into string
	function executeStmts($output)
	{
		$metadataCountTotal = 0;
		$this->userId = $this->session->getVar('setup_userId');
		$this->allIds = array();
		if($userBibCondition = $this->common->userBibCondition())
			$userBibCondition = " AND " . $userBibCondition;
		$order = " ORDER BY " . 
			$this->db->tidyInputClause('surname') . "," . 
			$this->db->tidyInputClause('year1') . "," . 
			$this->db->tidyInputClause('title') . "," . 
			$this->db->tidyInputClause('page_start') . '+ 0'; // read varchar as integer
		$conditionOrder = $userBibCondition . $order;
		if($this->stmtQuote)
		{
			$stmt = $this->stmtQuote . $this->kwq . $conditionOrder;
			$metadataCount = 
				$this->metadataCommon->executeThisStmt($stmt, "text", "quotes", 
				$this->allIds, $this->userId, $this->patterns);
			$metadataCountTotal += $metadataCount;
		}
		if($this->stmtQuoteComment)
		{
			$stmt = $this->stmtQuoteComment . $this->kwq . $conditionOrder;
			$metadataCount = 
				$this->metadataCommon->executeThisStmt($stmt, "comment", 
				"quoteComments", $this->allIds, $this->userId, $this->patterns);
			$metadataCountTotal += $metadataCount;
		}
		$pString = $this->metadataCommon->format('quotes');
		$pString .= $this->metadataCommon->format('quoteComments');
		if($this->stmtParaphrase)
		{
			$stmt = $this->stmtParaphrase . $this->kwp . $conditionOrder;
			$metadataCount = 
				$this->metadataCommon->executeThisStmt($stmt, "text", 
				"paraphrases", $this->allIds, $this->userId, $this->patterns);
			$metadataCountTotal += $metadataCount;
		}
		if($this->stmtParaphraseComment)
		{
			$stmt = $this->stmtParaphraseComment . $this->kwp . $conditionOrder;
			$metadataCount = 
				$this->metadataCommon->executeThisStmt($stmt, "comment", 
				"paraphraseComments", $this->allIds, $this->userId, $this->patterns);
			$metadataCountTotal += $metadataCount;
		}
		$pString .= $this->metadataCommon->format('paraphrases');
		$pString .= $this->metadataCommon->format('paraphraseComments');
		if($this->stmtMusing)
		{
			$stmt = $this->stmtMusing . $this->kwm . $conditionOrder;
			$metadataCount = 
				$this->metadataCommon->executeThisStmt($stmt, "text", "musings", 
				$this->allIds, $this->userId, $this->patterns);
			$metadataCountTotal += $metadataCount;
		}
		$pString .= $this->metadataCommon->format('musings');
		if(!$pString)
			return $this->messages->text("metadata", "noResultMeta");
		if($output == 'rtf')
		{
			if(($pString = $this->metadataCommon->createRtf($pString)) === FALSE)
				$this->badInput($this->errors->text("file", "write"));
			return $pString;
		}
// Write resource ids found here to session for use with previous and next icons when viewing a single resource.
		if(!empty($this->allIds))
			$this->session->setVar('list_allIds', base64_encode(serialize($this->allIds)));
		else
			$this->session->delVar("list_allIds");
// Get name of current bibliography
		$useBib = $this->session->getVar('mywikindx_bibliography_use');
		if($useBib)
		{
			$recordset = $this->db->select(array('WKX_user_bibliography'), array('title'), 
				" WHERE " . $this->db->formatfield('id') . "=" . $this->db->tidyInput($useBib));
			$row = $this->db->fetchRow($recordset);
			$bib = " (" . $this->messages->text("user", "bibliography") . ": " . 
				$this->html->dbToHtmlTidy($row['title']) . ")";
		}
		else
			$bib = " (" . $this->messages->text("user", "bibliography") . ": " . 
				$this->messages->text("user", "masterBib") . ")";
		return MISC::p($this->messages->text("hint", "displayMeta", 
			' ' . $metadataCountTotal . $bib)) . $pString;
	}
// write input to session
	function writeSession()
	{
// First, write all input with 'search_' prefix to session
		foreach($this->vars as $key => $value)
		{
			if(preg_match("/^searchMeta_/", $key))
			{
// Is this a multiple select box input?  If so, multiple choices are written to session as 
// comma-delimited string (no spaces).
// Don't write any FALSE or '0' values.
				if(is_array($value))
				{
					if(!$value[0] || ($value[0] == $this->messages->text("misc", "ignore")))
						unset($value[0]);
					if(empty($value))
					{
						$this->session->delVar($key);
						continue;
					}
					$value = implode(",", $value);
				}
// If this is a different listing to the previous one, reset the paging counter.
//				if($this->session->getVar("searchMeta_$key") != $value)
//					$this->session->delVar('mywikindx_pagingStart');
				if(!trim($value))
					continue;
				$temp[$key] = trim($value);
			}
		}
// remove search_partial and search_word if not checked or empty
		if(isset($temp))
		{
//			if(!array_key_exists('search_type', $temp))
//				$this->session->delVar('search_type');
			if(!array_key_exists('searchMeta_partial', $temp))
				$this->session->delVar('searchMeta_partial');
			if(!array_key_exists('searchMeta_word', $temp))
				$this->session->delVar('searchMeta_word');
			if(isset($temp))
				$this->session->writeArray($temp);
		}
	}
// validate user input - method, word and field are required.
// Input comes either from form input or, when paging, from the session.
	function checkInput()
	{
		$this->writeSession();
		if(array_key_exists("searchMeta_method", $this->vars) && $this->vars["searchMeta_method"])
			$type = $this->vars["searchMeta_method"];
		else if($this->session->issetVar('searchMeta_method'))
			$type = $this->session->getVar("searchMeta_method");
		else
			$this->badInput($this->errors->text("inputError", "missing"));
		if(array_key_exists("searchMeta_field", $this->vars) && $this->vars["searchMeta_field"])
			$type = $this->vars["searchMeta_field"];
		else if($this->session->issetVar('searchMeta_field'))
			$type = $this->session->getVar("searchMeta_field");
		else
			$this->badInput($this->errors->text("inputError", "missing"));
		if((array_key_exists("searchMeta_word", $this->vars) && !trim($this->vars["searchMeta_word"])) 
		|| !$this->session->getVar("searchMeta_word"))
			$this->badInput($this->errors->text("inputError", "missing"));
		return $this->session->getArray("searchMeta");
	}
// Error handling
	function badInput($error)
	{
		include_once("core/html/CLOSE.php");
		new CLOSE($this->db, $this->display($error));
	}
}
?>
